#include    <signal.h>
#include    <unistd.h>
#include	<stdio.h>

#include    <network/Socket.h>
#include    <network/Epollor.h>
#include    <thread/Singleton.h>
#include    <thread/TaskManager.h>
#include    <thread/Exception.h>
#include	<gflags/gflags.h>

#include    "CommandFactory.h"
#define LISTEN_PORT 3102
DEFINE_bool( daemon, false, "daemon the program" );
DEFINE_int32( port, 3101, "port to listen" );

int main(int argc,char *argv[])
{
    std::string helpMessage = "Usage:\t";
    helpMessage += argv[0];
    helpMessage += "\n\t--daemon=false|true";
    helpMessage += "\n\t\t: whether daemon the programe,default to false.";
    helpMessage += "\n\t--port=3101";
    helpMessage += "\n\t\t: port to listen,default to 3101.";
    helpMessage += "\n\t--help";
    helpMessage += "\n\t\t: show help information.";
    google::SetUsageMessage( helpMessage );
    google::ParseCommandLineFlags( &argc, &argv, true );
    if ( FLAGS_daemon ) {
        daemon(1, 0);
    }
    signal(SIGPIPE, SIG_IGN);

    Epollor::instance().start();
    ServerSocket *server = new ServerSocket( FLAGS_port );
    ListenedEpollChannelPtr channel
        = new ListenedEpollChannel( server );
    channel->setEvent(EPOLLIN|EPOLLERR|EPOLLHUP);
    Epollor::instance().registerChannel(channel);

    TaskManager::instance().initialize( 300 , 300 );

    while (true) {
        PacketPtr packet = PacketedChannelQueue::instance().getPacket();
        TaskPtr task = CommandFactory::instance().create(packet);
        if(task != 0) {
            TaskManager::instance().push(task);
        }
    }
    return 0 ;
}
